#!/bin/bash

root_uuid="9bd62a4e-80a9-4ec0-b727-05f4bc685107"
swap_uuid="9e92ce4a-901a-4354-a303-5f78fe31265b"
esp_uuid="41CE064C"
mount_dir=/mnt
bak_file=/data/route-sys-img.xz
efi_file=/data/route-sys-efi.tar.gz

err_exit() {
    echo "Error: "$1
    exit $2
}

backup() {
    cd /
    tar -cvpzf $mount_dir/$bak_file --exclude=/proc --exclude=/tmp      \
                    --exclude=/run  --exclude=/mnt --exclude=/dev       \
                    --exclude=/sys  --exclude=/boot/efi --exclude=/works /
    cd /boot/efi
    tar -cvpzf $mount_dir/$efi_file *
}

get_uuid() {
    echo $(blkid $1 | awk '{print $2}' | tr -d \")
}

create_part() {
    local dev_name="$1"
    gdisk $dev_name << EOF
o
Y
n


+2G
EF00
n


+1M
EF02
n


+4G
8200
n




w
Y
EOF
    partprobe

    test -e ${dev_name}1 || err_exit "gdisk..."

    mkfs -t vfat -i "$esp_uuid" ${dev_name}1 || err_exit "mkfs esp"
    mkswap -U "$swap_uuid" ${dev_name}2 || err_exit "mkfs swap"
    mkfs -t ext4 -U "$root_uuid" ${dev_name}3 || err_exit "mkfs root"
    mount ${dev_name}3 $mount_dir || err_exit "mount root"
    mkdir -p $mount_dir/boot/efi
    mount ${dev_name}1 $mount_dir/boot/efi || err_exit "mount efi"
    rm $mount_dir/lost+found -rf
}

get_install_dev() {
    mount | egrep -q '^/dev/sda' && echo '/dev/sdb' || echo '/dev/sda'
}

restore() {
    local dev_name=$(get_install_dev)
    create_part $dev_name
    tar -xvpf $bak_file -C $mount_dir || err_exit "tar xf root"

    mkdir $mount_dir/{proc,tmp,run,mnt,dev,sys}
    chmod 777 $mount_dir/tmp

    tar -xpf $efi_file -C $mount_dir/boot/efi/ || err_exit "tar xf efi"

    local oldbootname=$(efibootmgr | sed -rn -e 's/Boot(.*)\* Route/\1/p')
    test -z "$oldbootname" || efibootmgr -b "$oldbootname" -B
    efibootmgr -c -w -L Route -d $dev_name -p 1 -l \\EFI\\ubuntu\\grubx64.efi || err_exit "efibootmgr"

    reboot
}

cmd=${1-restore}

shift

$cmd $@

